import { ref, reactive, computed } from 'vue'
import { toast } from '@/utils'

// 列表，分页，搜索, 删除，修改状态
export function useInitTable(opt = {}) {
  const loading = ref(false)
  const tableData = ref([])
  const currentPage = ref(1)
  const total = ref(0)
  const limit = ref(10)

  let searchForm = null
  let resetSearchForm = null
  if (opt.searchForm) {
    // opt.searchForm不具备响应式，只有初始值
    searchForm = reactive({ ...opt.searchForm })
    resetSearchForm = () => {
      for (const key in opt.searchForm) {
        searchForm[key] = opt.searchForm[key]
      }

      getData()
    }
  }

  // 初始化table数据
  function getData(p) {
    if (typeof p === 'number') {
      currentPage.value = p
    }
    loading.value = true
    opt
      .getlist(currentPage.value, searchForm)
      .then((res) => {
        if (
          opt.onGetListSuccess &&
          typeof opt.onGetListSuccess === 'function'
        ) {
          opt.onGetListSuccess(res)
        } else {
          tableData.value = res.list
          total.value = res.totalCount
        }
      })
      .finally(() => (loading.value = false))
  }

  getData()

  // 删除
  function handleDelete(id) {
    loading.value = true
    opt
      .delete(id)
      .then((res) => {
        toast('删除成功')
        getData()
      })
      .finally(() => (loading.value = false))
  }

  // 批量删除
  const multiSelectionIds = ref([])
  const multipleTableRef = ref(null)
  function handleSelectionChange(val) {
    multiSelectionIds.value = val.map((o) => o.id)
  }
  function handleMultiDelete() {
    loading.value = true
    opt
      .delete(multiSelectionIds.value)
      .then((res) => {
        toast('批量删除成功')
        getData()
        multipleTableRef.value && multipleTableRef.value.clearSelection()
      })
      .finally(() => (loading.value = false))
  }

  // 批量修改状态
  function handleMultiStatusChange(status) {
    loading.value = true
    opt
      .updateStatus(multiSelectionIds.value, status)
      .then((res) => {
        toast('批量修改状态成功')
        getData()
        multipleTableRef.value && multipleTableRef.value.clearSelection()
      })
      .finally(() => (loading.value = false))
  }

  // 身份切换
  function handleStatusChange(status, row) {
    row.statusLoading = true
    opt.updateStatus &&
      opt
        .updateStatus(row.id, status)
        .then((res) => {
          toast('切换成功')
          row.status = status
        })
        .finally(() => {
          // getData()
          row.statusLoading = false
        })
  }

  return {
    searchForm,
    resetSearchForm,
    multipleTableRef,
    tableData,
    loading,
    currentPage,
    total,
    limit,
    getData,
    handleDelete,
    handleStatusChange,
    handleSelectionChange,
    handleMultiStatusChange,
    handleMultiDelete,
    multiSelectionIds
  }
}

// 表单的新增和修改
export function useInitForm(opt = {}) {
  // 表单
  const formDrawerRef = ref(null)
  const formRef = ref(null)
  const form = reactive({})
  const rules = opt.rules || {}
  const editId = ref(0)
  const drawerTitle = computed(() => (editId.value ? '修改' : '新增'))

  // 表单提交，修改，新增
  const handleSumbit = () => {
    formRef.value.validate((valid) => {
      if (!valid) {
        return
      } else {
        formDrawerRef.value.showLoading()

        // 提交之前需要数据转变
        let body = null
        if (opt.beforeSumbit && typeof opt.beforeSumbit === 'function') {
          body = opt.beforeSumbit({ ...form })
        } else {
          body = form
        }

        const fn = editId.value
          ? opt.update(editId.value, body)
          : opt.create(body)

        fn.then(() => {
          toast(drawerTitle.value + '成功')
          formDrawerRef.value.close()
          opt.getData(editId.value ? false : 1)
        }).finally(() => {
          formRef.value.resetFields()
          formDrawerRef.value.hideLoading()
        })
      }
    })
  }

  // 编辑前，点击编辑按钮
  const handleEdit = (row) => {
    editId.value = row.id
    resetForm(row)
    formDrawerRef.value.open()
  }

  // 新增前，点击新增按钮,
  const handleCreate = () => {
    editId.value = 0
    resetForm(opt.form)
    formDrawerRef.value.open()
  }

  function resetForm(row = false) {
    formRef.value && formRef.value.clearValidate()

    if (row) {
      for (const key in opt.form) {
        form[key] = row[key]
      }
    }
  }

  // 表单取消
  const handleCancel = () => {
    formRef.value.resetFields()
    formDrawerRef.value.close()
  }

  return {
    formRef,
    formDrawerRef,
    form,
    rules,
    drawerTitle,
    editId,
    handleCreate,
    handleEdit,
    handleSumbit,
    handleCancel,
  }
}
